const BASE_URL = "http://8.130.129.209/";

/**
 * url 请求地址
 * data 请求参数
 * method 请求方法
 */
function request(url, data = {}, method = "GET") {
  wx.showLoading({
    title: '加载ing...',
    mask:true
  })
  // 接收参数
  if (typeof url == "object") {
    data = url.data;
    method = url.method;
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: `${BASE_URL}${typeof url == "object" ? url.url : url}`,
      data: data,
      method: method,
      header: {
        token: wx.getStorageSync('token')
      },
      success: async function (res) {
        if(res.data.msg == '请先登录') {
          wx.login({
            success: (code) => {
              // 获取微信运动步数
              wx.getWeRunData({
                success: (rundata) => {
                  wx.request({
                    url: `${BASE_URL}/index.php/api/index/getcode`,
                    data: {
                      code: code.code,
                      encryptedData: rundata.encryptedData,
                      iv: rundata.iv,
                    },
                    method: 'POST',
                    success: function (res) {
                      wx.setStorageSync("token", res.data.data.token);
                      // 获取所有页面栈
                      let pages = getCurrentPages();
                      // 获取页面栈当前页面
                      let currentPage = pages[pages.length - 1];
                      currentPage.onLoad();

                    },
                    fail: (err) => {
                      console.log(err);
                    },
                  })
                },
                fail: (err) => {
                  console.log(err);
                },
              });
            },
          })

          return reject(res.data.msg)
        }
        if(res.data.code != 0) {
          wx.showToast({
            title: res.data.msg,
          })
          return reject(res.data.msg)
        }
        resolve(res.data.data); // 成功
        wx.hideLoading()
      },
      fail: function (error) {
        reject(error);
        wx.hideLoading()
      },
    });
  });
}
function get(url, data) {
  return request(url, data, "GET");
}
function post(url, data) {
  return request(url, data, "POST");
}
function put(url, data) {
  return request(url, data, "PUT");
}

// 导出方法
module.exports = {
  get,
  post,
  put,
  delete: (url, data) => {
    return request(url, data, "DELETE");
  },
  request,
};
